package com.um.jdy.app.shop.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.um.jdy.app.activity.entity.vo.GoodsActivityVO;
import com.um.jdy.app.activity.entity.vo.GoodsCouponsVO;
import com.um.jdy.app.activity.manager.ActivityManager;
import com.um.jdy.app.activity.manager.CouponsManager;
import com.um.jdy.app.shop.entity.dto.GoodsCommentPageDTO;
import com.um.jdy.app.shop.entity.dto.GoodsPageDTO;
import com.um.jdy.app.shop.entity.vo.GoodsCommentItemVO;
import com.um.jdy.app.shop.entity.vo.GoodsDetailVO;
import com.um.jdy.app.shop.entity.vo.GoodsItemVO;
import com.um.jdy.app.shop.entity.vo.GoodsRecomendItemVO;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.jdy.common.shop.code.ShopGoodsCode;
import com.um.jdy.common.shop.entity.po.Goods;
import com.um.jdy.common.shop.entity.po.GoodsCollection;
import com.um.jdy.common.shop.entity.po.GoodsOption;
import com.um.jdy.common.shop.entity.po.GoodsRecord;
import com.um.jdy.common.shop.entity.vo.GoodsOptionVO;
import com.um.jdy.common.shop.entity.vo.GoodsVO;
import com.um.jdy.common.shop.service.GoodsCollectionService;
import com.um.jdy.common.shop.service.GoodsOptionService;
import com.um.jdy.common.shop.service.GoodsRecordService;
import com.um.jdy.common.shop.service.GoodsService;
import com.um.springboot.starter.config.SystemSQL;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.utils.condition.ConditionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * @Title
 * @Description
 * @Author renjunwei
 * @Date 2023/5/22 10:37
 */
@Slf4j
@Service
public class GoodsManager {

    @Autowired
    GoodsService goodsService;

    @Autowired
    GoodsOptionService goodsOptionService;

    @Autowired
    GoodsCollectionService goodsCollectionService;

    @Autowired
    MemberUserService userService;

    @Autowired
    GoodsCommentManager goodsCommentManager;

    @Autowired
    GoodsRecordService goodsRecordService;

    @Autowired
    ActivityManager activityManager;

    @Autowired
    private CouponsManager couponsManager;

    /**
     * 分页查询商品
     * @param dto
     * @return
     */
    public Page<GoodsItemVO> getPage(GoodsPageDTO dto){
        Page page = new Page(dto);

        Map<String, String> condition = ConditionBuilder.create()
                .put("g.code", dto.getCode())
                .put("g.com_id",goodsService.getComId())
                .putLike("g.shop_goods_name", dto.getShopGoodsName())
                .build();

        List<GoodsPageDTO.Sort> sorts = Optional.ofNullable(dto.getSorts()).orElseGet(() -> new ArrayList());
        String[] filed = sorts.stream().map(item -> item.getFiled().getValue()).toArray(String[]::new);
        String[] sort = sorts.stream().map(item -> item.getOrder().name()).toArray(String[]::new);
        return goodsService.getCMSViewModelPageBySqlName(page, "get_goods_page", "get_goods_count",
                GoodsItemVO.class, condition.keySet().toArray(new String[0]), condition.values().toArray(new String[0]),
                new ArrayList(), filed, sort);
    }

    /**
     * 查询商品详情
     * @param shopGoodsId
     * @return
     */
    public GoodsDetailVO get(String shopGoodsId){
        Goods goods = goodsService.getEntity(shopGoodsId);
        if(null == goods){
            throw new ServiceException(ShopGoodsCode.GoodsNotExist);
        }

        String userId = userService.get().getMemberUserId();

        //商品规格
        List<GoodsOptionVO> optionList = getOptionList(shopGoodsId);
        Integer totalStock = optionList.stream().mapToInt(item -> item.getStock()).sum();

        //商品收藏
        GoodsCollection goodsCollection = goodsCollectionService.getEntity(new String[]{"member_user_id", "shop_goods_id", "is_collection"},
                new Object[]{userId, shopGoodsId, YesOrNo.Yes.name()});

        //评论总数
        Integer commentsNum = goodsService.getObjectBySqlName("get_goods_comment_num", new String[]{shopGoodsId,goodsService.getComId()}, Integer.class);

        //销量
        Integer orderNum = goodsService.getObjectBySqlName("get_goods_order_num", new String[]{shopGoodsId,goodsService.getComId()}, Integer.class);

        //精选评价
        GoodsCommentPageDTO goodsCommentPageDTO = new GoodsCommentPageDTO();
        goodsCommentPageDTO.setPage_no(1);
        goodsCommentPageDTO.setPage_size(3);
        goodsCommentPageDTO.setIs_quality(YesOrNo.Yes.name());
        goodsCommentPageDTO.setShop_goods_id(shopGoodsId);
        Page<GoodsCommentItemVO> qualityComment = goodsCommentManager.getGoodsCommentPage(goodsCommentPageDTO);

        //推荐商品
        List<GoodsVO> recommendGoods = this.getRecommendGoods(goods.getCode());

        // //精选买家秀
        // Page buyerShowPage = socialNotesService.getBuyerShowPage(0,4,mallGoodsId,"",YesOrNo.YES.getKey());

        //商品可用的优惠券
        List<GoodsCouponsVO> couponsList = couponsManager.getCouponsListByGoods(shopGoodsId);

        // 活动
        GoodsActivityVO activity = activityManager.getActivityByGoods(shopGoodsId);

        addRecord(userId, shopGoodsId);

        GoodsDetailVO goodsDetail = new GoodsDetailVO();
        goodsDetail.setGoods(BeanUtil.toBean(goods, GoodsVO.class));
        goodsDetail.setTotalStock(totalStock);
        goodsDetail.setOptionList(optionList);
        goodsDetail.setCommentCount(commentsNum);
        goodsDetail.setOrderNum(orderNum);
        goodsDetail.setIsCollection(null != goodsCollection);
        goodsDetail.setRecommendGoods(recommendGoods);
        goodsDetail.setQualityComments(BeanUtil.copyToList(qualityComment.getResult(), GoodsCommentItemVO.class));
        goodsDetail.setQualityCommentCount((int)qualityComment.getTotalCount());
        goodsDetail.setCoupons(couponsList);
        goodsDetail.setActivity(activity);
        return goodsDetail;
    }

    /**
     * 查询商品规格
     * @param shopGoodsId
     * @return
     */
    public List<GoodsOptionVO> getOptionList(String shopGoodsId){
        //商品规格
        List<GoodsOption> optionList = goodsOptionService.getList("shop_goods_id", shopGoodsId);
        return BeanUtil.copyToList(optionList, GoodsOptionVO.class);
    }

    /**
     * 查询推荐商品
     */
    public List<GoodsVO> getRecommendGoods(String codeStr){
        List<GoodsVO> goodsList = goodsService.getViewModelList("get_goods_recommend_by_code",
                GoodsVO.class, new String[]{goodsService.getComId(),codeStr});
        // 临时处理， 没有推荐的就随便查一点
        if(null == goodsList || goodsList.isEmpty()){
            List<GoodsItemVO> result = getPage(new GoodsPageDTO(1, 20)).getResult();
            return BeanUtil.copyToList(result, GoodsVO.class);
        }
        return goodsList;
    }

    /**
     * 查询推荐商品
     */
    public List<GoodsRecomendItemVO> getRecommendGoods(String recommendType, Integer limit){
        if(null != limit && limit > 0){
            String sql = SystemSQL.getInstance().getSystemSQL("get_goods_recommend_list");
            return goodsService.getViewModelListBySQL(sql + " limit " + limit,
                    GoodsRecomendItemVO.class, new String[]{recommendType});
        }
        return goodsService.getViewModelList("get_goods_recommend_list", GoodsRecomendItemVO.class,
                new String[]{recommendType,goodsService.getComId()});
    }

    /**
     * 添加商品阅读记录
     * @param userId
     * @param shopGoodsId
     */
    private void addRecord(String userId, String shopGoodsId){
        GoodsRecord goodsRecord = goodsRecordService.getEntity(new String[]{"member_user_id","shop_goods_id"},new String[]{userId,shopGoodsId});
        if(null == goodsRecord){
            goodsRecord = new GoodsRecord();
            goodsRecord.setMemberUserId(userId);
            goodsRecord.setShopGoodsId(shopGoodsId);
        }
        goodsRecord.setCreateTime(DateUtil.date());
        goodsRecordService.save(goodsRecord);
    }

}
